package conf

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/xormplus/xorm"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"log"
)

type ServiceCfg struct {
	Port   string `yaml:"port"`
	Expire int64  `yaml:"expire"`
	Db     struct {
		Host     string `yaml:"host"`
		Port     string `yaml:"port"`
		User     string `yaml:"user"`
		Password string `yaml:"password"`
		DbName   string `yaml:"db_name"`
		Debug    bool   `yaml:"debug"`
	}
}

var (
	Config   *ServiceCfg
	DbEngine *xorm.Engine
)

func init() {
	getGlobalConfig()
	args := Config.Db.User + ":" + Config.Db.Password + "@tcp(" + Config.Db.Host + ":" + Config.Db.Port + ")/" + Config.Db.DbName + "?charset=utf8"
	db, err := xorm.NewEngine("mysql", args)
	if err != nil || db == nil {
		log.Fatalln("DataBase init error:", err)
	}
	DbEngine = db
	//DbEngine.ShowSQL(true)
	DbEngine.ShowSQL(Config.Db.Debug)
}

func getGlobalConfig() {
	yamlFile, err := ioutil.ReadFile("./config_file/global.yaml")
	if err != nil {
		log.Fatalln(err)
		return
	}
	err = yaml.Unmarshal(yamlFile, &Config)
	if err != nil {
		log.Fatalln(err)
		return
	}
	fmt.Printf("Config %+v\n", Config)
}
